package com.project.communitymanagement.auth.common;

import com.alibaba.fastjson.JSONObject;
import com.project.communitymanagement.entity.TbOwner;
import com.project.communitymanagement.mapper.TbOwnerMapper;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xgp
 * @version 1.0
 * @date 2020/5/6 13:26
 * @Annotate 登入成功处理逻辑类
 */
@Component
@Log4j2
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private TbOwnerMapper tbOwnerMapper;

    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        JSONObject jsonObject = new JSONObject();
        String username = ((User) authentication.getPrincipal()).getUsername();
        TbOwner user = tbOwnerMapper.getUserByUsername(username);
        /*      com.setup.health.entity.User user = mapper.getUserByUsername(username);
        *//**修改登录时间增加登录次数*//*
        com.setup.health.entity.User userUpdate = new com.setup.health.entity.User();
        userUpdate.setId(user.getId());
        userUpdate.setLogin_date(new Date());
        userUpdate.setLogin_count((user.getLogin_count() == null ? 0 : user.getLogin_count()) + 1);
        mapper.updateByPrimaryKeySelective(userUpdate);
        UserRoleFinal.concurrentHashMap.put(user.getUsername(), user.getRole());*/
        jsonObject.put("code", 200);
        jsonObject.put("message", "SUCCESS");
        jsonObject.put("data", user);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(jsonObject.toJSONString());
        logger.info("登录成功,{}", authentication);
    }
}
